<template>
  <div id="checkregistDiv">
    <div class="bodyContent">

      <div class="area margin-top-xs">
        <Splitpanes class="SplitpanesAll" :dbl-click-splitter="false">
          <Pane size="18">
            <vxe-toolbar class-name="bg-grey light" className="bg-grey light">
              <template #buttons>
                <div class="padding-lr-xs" style="width:100%">
                  <vxe-form :data="searchForm" ref="xFormBase" class-name="bg-grey light" className="bg-grey light" title-align="left" title-width="60">
                    <vxe-form-item title="登记日期" span="24" field="reqTime">
                      <template #default="{ data }">
                        <vxe-input v-model="data.reqTime" type="date" :value-format="'yyyy-MM-dd'" :label-format="'yyyy-MM-dd'" transfer @change="timeChange"></vxe-input>
                      </template>
                    </vxe-form-item>
                  </vxe-form>
                </div>
              </template>
            </vxe-toolbar>
            <div id="checkregistDiv2" style="height: calc(100% - 30px - 75px)" class="padding-lr-xs">
              <el-scrollbar style="height: calc(100%)">
                <vxe-form :data="reqMainForm" ref="wlconfigpatsettingForm" class-name="form-pat-info margin-bottom form-size-auto" className="" title-align="left" title-width="60">
                  <vxe-form-item title="样本条码" span="24" field="reqNo">
                    <template #default="{ data }">
                      <vxe-input ref="reqNoInput" v-model="data.reqNo" @keydown="reqNoKeyupEnter" v-enterNextInput class="enterNextInputFlag" clearable></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="病人代号" span="24" field="reqNo">
                    <template #default="{ data }">
                      <vxe-input ref="patNoInput" v-model="data.patNo" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable :disabled="calcIsDisabled()"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="病人类型" span="24" field="patType">
                    <template #default="{ data }">
                      <VxeDictSelection v-enterNextInput :isChild="false" :tableColumn="[
                        { field: 'code', title: '编码', width: `60px` },
                        { field: 'name', title: '名称', minWidth: `80px` }
                      ]" :url="`/api/sys/basDictDetail/findDictDetailList`" ref="patTypeDictpdown" :displayTextObj="data.patTypeNa ? data.patTypeNa : ''" @confirmClick="SelectRowClick" :aimKeys="[
                        { aimKey: 'patTypeNa', rowKey: 'name' },
                        { aimKey: 'patType', rowKey: 'code' }
                      ]" :dataObj="{ code: 'PATTYPE' }" :isDisabled="calcIsDisabled()"></VxeDictSelection>

                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="姓名" span="24" field="reqNo">
                    <template #default="{ data }">
                      <vxe-input v-model="data.patNa" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable :disabled="calcIsDisabled()"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="性别" span="24" field="sex">
                    <template #default="{ data }">
                      <VxeDictSelection ref="sexDictpdown" v-enterNextInput :isChild="false" :tableColumn="[
                        { field: 'code', title: '编码', width: `60px` },
                        { field: 'name', title: '名称', minWidth: `80px` }
                      ]" :url="`/api/sys/basDictDetail/findDictDetailList`" :displayTextObj="data.sexNa ? data.sexNa : ''" @confirmClick="SelectRowClick" :aimKeys="[
                          { aimKey: 'sexNa', rowKey: 'name' },
                          { aimKey: 'sex', rowKey: 'code' }
                        ]" :dataObj="{ code: 'sex' }" :isDisabled="calcIsDisabled()"></VxeDictSelection>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="出生日期" span="24" field="birthDay">
                    <template #default="{ data }">
                      <vxe-input v-model="data.birthDay" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" type="datetime" v-enterNextInput class="enterNextInputFlag" style="width: 100%" clearable transfer :disabled="calcIsDisabled()"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="年龄" span="24" field="sex">
                    <template #default="{ data }">
                      <AgeComp class="enterNextInputFlag" :ageObj="{ age: data.age, ageUnit: data.ageUnit }" @ageChange="ageChange" :isDisabled="calcIsDisabled()" />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="联系电话" span="24" field="telNo">
                    <template #default="{ data }">
                      <vxe-input v-model="data.telNo" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable :disabled="calcIsDisabled()"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="证件号码" span="24" field="idNo">
                    <template #default="{ data }">
                      <vxe-input v-model="data.idNo" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable :disabled="calcIsDisabled()"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="标本类型" span="24" field="sampleType">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="sampleTypePdown" :url="'/api/lab/labSampleType/findSampleTypeList'" @confirmClick="SelectRowClick" :tableColumn="[
                         { type: 'seq', title: '#', width: '30px' },
                          { field: 'sampleTypeName', title: '名称' },
                          { field: 'sampleTypeCode', title: '编码' }
                        ]" :aimKeys="[
                         { aimKey: 'sampleTypeNa', rowKey: 'sampleTypeName' },
                          { aimKey: 'sampleType', rowKey: 'sampleTypeCode' }
                        ]" :displayTexts="['sampleTypeNa']" :displayTextObj="data.sampleTypeNa ? data.sampleTypeNa : ''" :dataObj="null" :isDisabled="calcIsDisabled()" />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="检验目的" span="24" field="reqPurpose">
                    <template #default="{ data }">
                      <vxe-textarea v-model="data.reqPurpose" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable :disabled="calcIsDisabled()"></vxe-textarea>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="科室" span="24" field="reqDept">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="reqDeptDdown" :url="'/api/sys/findDepartmentListbyCurrentUserOrg'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'name', title: '名称' },
                          { field: 'code', title: '编码' }
                        ]" :aimKeys="[
                          { aimKey: 'reqDeptNa', rowKey: 'name' },
                          { aimKey: 'reqDept', rowKey: 'code' }
                        ]" :displayTexts="['reqDeptNa']" :displayTextObj="data.reqDeptNa ? data.reqDeptNa : ''" :dataObj="null" :isDisabled="calcIsDisabled()" />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="床号" span="24" field="bedNo">
                    <template #default="{ data }">
                      <vxe-input v-model="data.bedNo" @blur="reqMainFormChange($event)" @clear="reqMainFormChange($event)" v-enterNextInput class="enterNextInputFlag" clearable :disabled="calcIsDisabled()"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="申请时间" span="24" field="reqTime">
                    <template #default="{ data }">
                      <vxe-input v-model="data.reqTime" type="datetime" v-enterNextInput class="enterNextInputFlag" style="width: 100%" clearable transfer :disabled="calcIsDisabled()"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="申请医师" span="24" field="reqDoctor">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="reqDoctorPdown" :url="'/api/sys/hisEmployee/finAllHisEmployeeList'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'name', title: '名称' },
                          { field: 'code', title: '编码' }
                        ]" :aimKeys="[
                          { aimKey: 'reqDoctorNa', rowKey: 'name' },
                          { aimKey: 'reqDoctor', rowKey: 'code' }
                        ]" :displayTexts="['reqDoctorNa']" :displayTextObj="data.reqDoctorNa ? data.reqDoctorNa : ''" :dataObj="null" :isDisabled="calcIsDisabled()" />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="采样时间" span="24" field="samplingTime">
                    <template #default="{ data }">
                      <vxe-input v-model="data.samplingTime" @change="reqMainFormChange($event)" @clear="reqMainFormChange($event)" type="datetime" v-enterNextInput class="enterNextInputFlag" style="width: 100%" clearable transfer :disabled="calcIsDisabled()"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="采样医师" span="24" field="samplingDoctor">
                    <template #default="{ data }">
                      <VxePulldownSelection v-enterNextInput :isChild="false" ref="samplingDoctorPdown" :url="'/api/user/getUserInfoList'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'realname', title: '名称' },
                          { field: 'username', title: '编码' }
                        ]" :aimKeys="[
                           { aimKey: 'samplingDoctorNa', rowKey: 'realname' },
                          { aimKey: 'samplingDoctor', rowKey: 'username' }
                        ]" :displayTexts="['samplingDoctorNa']" :displayTextObj="data.samplingDoctorNa ? data.samplingDoctorNa : ''" :dataObj="null" :isDisabled="calcIsDisabled()" />
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </el-scrollbar>
            </div>
          </Pane>
          <Pane size="38">
            <Splitpanes horizontal class="horizontalLine">
              <Pane size="60">
                <vxe-toolbar perfect>
                  <template #buttons>
                    <span class="padding-lr-xs">
                      <vxe-button type="text" class="button-blue" content="刷新" @click="findReqDetailList(false)"></vxe-button>
                    </span>
                    <span class="padding-lr-xs">
                      <vxe-button type="text" content="删除" class-name="padding-lr-xs" class="button-red padding-lr-xs" @click="deleteReqDetailList" />
                    </span>
                    <span class="padding-lr-xs">
                      <vxe-button type="text" class="button-blue" content="上个" @click="prevReqCode"></vxe-button>
                      <vxe-button type="text" class="button-blue" content="下个" @click="nextReqCode"></vxe-button>
                    </span>
                  </template>
                </vxe-toolbar>
                <div class="tableMoSaBox">
                  <vxe-table ref="reqDetailTableRef" :data="reqDetailList" :loading="dLoading" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source :checkbox-config="{
                      checkMethod: checCheckboxkMethod2,
                    }">
                    <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
                    <vxe-column type="seq" width="24" fixed="left"></vxe-column>
                    <vxe-column field="feeCode" title="收费项目代号" width="90"></vxe-column>
                    <vxe-column field="feeName" title="收费项目名称" min-width="120"></vxe-column>
                    <vxe-column field="price" title="单价" width="100"></vxe-column>
                    <vxe-column field="amount" title="数量" width="100"></vxe-column>
                    <vxe-column field="costs" title="金额" width="80px" align="right"></vxe-column>
                  </vxe-table>
                </div>
              </Pane>
              <Pane size="40">
                <Splitpanes class="Splitpanes" :dbl-click-splitter="false">
                  <Pane size="30">
                    <vxe-table ref="barCodeTypeTable" border class="mytable-scrollbar" show-header-overflow show-overflow align="center" :row-config="{ isCurrent: true, isHover: true }" @current-change="barCodeRowClick" :data="barCodeList" :loading="showLoading">
                      <vxe-column field="color" title="颜色" width="75" :edit-render="{ autofocus: '.vxe-input--inner' }">
                        <template #default="{ row }">
                          <el-tag class="margin-lr-xs" :style="{ background: row.color ? row.color : '' }" v-if="row.color"></el-tag>
                        </template>
                      </vxe-column>
                      <vxe-column field="barcodeNa" title="分类名称"> </vxe-column>
                    </vxe-table>
                  </Pane>
                  <Pane size="70">
                    <vxe-table ref="feeItemTableRef" :data="feeItemList" :loading="feeLoading" @checkbox-change="feeItemChangeRow" height="auto" class="mytable-scrollbar" border="inner" align="center" :column-config="{ resizable: true }" resizable show-overflow keep-source :checkbox-config="{
                      checkMethod:checCheckboxkMethod2,
                    }">
                      <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
                      <vxe-column type="seq" title="序号" width="30"></vxe-column>
                      <vxe-column field="feeCode" title="项目编号" width="70" align="left"></vxe-column>
                      <vxe-column field="feeName" title="项目名称" min-width="160" align="left"></vxe-column>
                      <vxe-column field="price" title="单价" width="70"></vxe-column>
                    </vxe-table>
                  </Pane>
                </Splitpanes>
              </Pane>
            </Splitpanes>
          </Pane>
          <Pane size="44">
            <vxe-toolbar class-name="bg-orange light">
              <template #buttons>
                <span class="padding-lr-xs">
                  <vxe-button type="text" :loading="mLoading" content="刷新" class-name="padding-lr-xs" class="button-blue padding-lr-xs" @click="findReqMainList" />
                </span>
                <span class="padding-lr-xs">
                  <vxe-button type="text" content="删除" class-name="padding-lr-xs" class="button-red padding-lr-xs" @click="deleteReqMain" />
                </span>
              </template>
            </vxe-toolbar>
            <div class="tableBox">
              <vxe-table ref="reqMainTableRef" :data="reqMainList" :loading="mLoading" @current-change="reqMainRowClick" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                <vxe-column field="reqNo" title="样本条码" width="150"> </vxe-column>
                <vxe-column field="stateNa" title="状态" width="80"></vxe-column>
                <vxe-column field="patNo" title="病人代号" width="100"></vxe-column>
                <vxe-column field="patNa" title="姓名" width="100"></vxe-column>
                <vxe-column field="sexNa" title="性别" width="100"></vxe-column>
                <vxe-column field="ageStr" title="年龄" width="100"></vxe-column>
                <vxe-column field="sampleTypeNa" title="标本类型" width="100"></vxe-column>
                <vxe-column field="reqDeptNa" title="科室" width="100"></vxe-column>
                <vxe-column field="bedNo" title="床号" width="100"></vxe-column>
                <vxe-column field="reqTime" title="申请时间" width="100"></vxe-column>
                <vxe-column field="reqDoctorNa" title="申请医师" width="100"></vxe-column>
                <vxe-column field="samplingTime" title="采样时间" width="100"></vxe-column>
                <vxe-column field="samplingDoctorNa" title="采样医师" width="100"></vxe-column>
              </vxe-table>
            </div>
          </Pane>
        </Splitpanes>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, ObjectDirective } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { IsEmpty, formatDateTime, autoIncrementNumber, sortByField } from '@/utils/common';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import { AppStore } from '@/stores/store'; //'../../../stores/store';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import VxeDictSelection from '@/components/VxeDictSelection.vue';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';

import AgeComp from '@/components/AgeComp.vue';

let store = AppStore();
let reqMainList: any = reactive([]);
let reqDetailList: any = reactive([]);
let barCodeList = reactive([]);
let feeItemList = reactive([]);
let showLoading = ref(false); //刷新+表格加载
let feeLoading = ref(false); //刷新+表格加载
let dLoading = ref(false);
let mLoading = ref(false);
let sltReqMain: any = reactive({});
let sltInCompany: any = reactive({});
let selevctBarCodeRow: any = reactive({});
let searchForm = reactive({
  searchValue: '',
  reqTime: formatDateTime(new Date(), 'yyyy-MM-dd')
});

let reqMainForm = reactive({
  id: null,
  reqNo: '',
  state: '',
  inspectCompany: '',
  inspectCompanyName: '',
  patType: '',
  patTypeNa: '',
  patNo: '',
  patNa: '',
  sex: '',
  sexNa: '',
  birthDay: '',
  age: null,
  ageUnit: '',
  ageStr: '',
  telNo: '',
  sampleType: '',
  sampleTypeNa: '',
  idNo: '',
  reqPurpose: '',
  bedNo: '',
  reqDept: '',
  reqDeptNa: '',
  reqDoctor: '',
  reqDoctorNa: '',
  reqTime: '',
  samplingDoctor: '',
  samplingDoctorNa: '',
  samplingTime: '',
  orgId: ''
});

// 方法定义区 =============
// 页面加载时更新用户/角色列表
onMounted(async () => {
  const res: any = await findCompanyUserList();
  if (res.status.code === 1) {
    sltInCompany = res.data[0];
  }
  getBarCodeList();
  findReqMainList(false);
});

async function findCompanyUserList() {
  return new Promise((resolve, reject) => {
    const url = '/lab/inspectCompanyUser/findInspectCompanyUserList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: {
          username: store.userInfo.username
        }
      })
      .then((res: any) => {
        resolve(res);
      })
      .catch((err: any) => {
        // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
      });
  });
}

async function findReqMainList(isnotRefresh) {
  if (IsEmpty(sltInCompany)) {
    VxeMessage('当前用户为对照送检单位', VxeNotifyType.error);
    return;
  }

  mLoading.value = true;
  reqMainList.length = 0; //放入数据前清空数据
  const url = '/lab/reqMain/findReqMainList';
  await proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchForm.searchValue,
        reqTime: searchForm.reqTime,
        companyCode: sltInCompany.companyCode
      }
    })
    .then((res: any) => {
      reqMainList.push(...res.data);
      if (reqMainList.length == 0) {
        sltReqMain = {};
        clearReqMainForm();
        if (!IsEmpty(searchForm.reqTime)) {
          reqMainForm.reqNo = searchForm.reqTime.substring(0, 4) + searchForm.reqTime.substring(5, 7) + searchForm.reqTime.substring(8, 10) + '001';
        }
        reqDetailList.length = 0;
        //feeItemList.length = 0;
        const $table = proxy.$refs.feeItemTableRef;
        if ($table) {
          $table.clearCheckboxRow();
        }
      } else {
        const kn = reqMainList.find((k: any) => k.id == sltReqMain.id);
        if (IsEmpty(kn)) {
          reqMainRowClick({ row: reqMainList[reqMainList.length - 1], isnotRefresh }); //默认选中第一条数据
        } else {
          reqMainRowClick({ row: kn, isnotRefresh }); //默认选中第一条数据
        }
      }

      mLoading.value = false;
    })
    .catch((err: any) => {
      mLoading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function timeChange() {
  findReqMainList(false);
}

function reqNoKeyupEnter({ value, $event }: any) {
  if ($event.keyCode == 13) {
    //首先从列表中获取数据 reqMainList
    const rmObj = reqMainList.find((item: any) => item.reqNo == reqMainForm.reqNo);
    if (IsEmpty(rmObj)) {
      (proxy.$refs.reqMainTableRef as any).clearCurrentRow();
      const reqNo = reqMainForm.reqNo;
      clearReqMainForm();
      sltReqMain = {};
      reqDetailList.length = 0;
      //feeItemList.length = 0;
      const $table = proxy.$refs.feeItemTableRef;
      if ($table) {
        $table.clearCheckboxRow();
      }
      reqMainForm.reqNo = reqNo;
      reqMainForm.reqTime = searchForm.reqTime + ' 00:00:00';
    } else {
      reqMainRowClick({ row: rmObj }); //默认选中第一条数据
    }

    //patNoInput.value?.focus();
  }
}
const patNoInput = ref(null); /*条码号 输入框 Ref对象*/

function reqMainFormChange(e) {
  if (IsEmpty(reqMainForm.id) && IsEmpty(e.value)) {
    return;
  }
  saveReqMainForm();
}
function ageChange(ageObj) {
  if (IsEmpty(reqMainForm.id)) {
    return;
  }
  Object.assign(reqMainForm, ageObj);
  reqMainForm.ageStr = ageObj.age + ageObj.ageUnit;
  saveReqMainForm();
}

function saveReqMainForm() {
  if (IsEmpty(reqMainForm.reqTime) || IsEmpty(reqMainForm.reqNo)) {
    return;
  }
  if (IsEmpty(reqMainForm.id)) {
    //新增
    const url = '/lab/reqMain/addReqMain';
    let reqMainData = {} as any;
    Object.assign(reqMainData, reqMainForm);
    if (!IsEmpty(sltInCompany)) {
      reqMainData.inspectCompany = sltInCompany.companyCode;
    }
    reqMainData.state = '10';
    reqMainData.stateNa = '申请';
    proxy.$http
      .post(url, reqMainData)
      .then((res: any) => {
        if (res.status.code === 1) {
          sltReqMain = res.data;
          findReqMainList(false);
        } else {
          VxeMessage('新增失败', VxeNotifyType.error);
        }
        //findQiIndexSqlOne();
      })
      .catch((err: any) => {
        console.log(err);
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    //修改
    const url = '/lab/reqMain/updateReqMain';
    let reqMainData = {} as any;
    Object.assign(reqMainData, reqMainForm);
    proxy.$http
      .post(url, reqMainData)
      .then((res: any) => {
        if (res.status.code === 1) {
          sltReqMain = res.data;
          findReqMainList(true);
        } else {
          VxeMessage('新增失败', VxeNotifyType.error);
        }
        //findQiIndexSqlOne();
      })
      .catch((err: any) => {
        console.log(err);
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  }
}

async function deleteReqMain() {
  if (calcIsDisabled()) {
    VxeMessage('该数据已审核或上机，不能删除', VxeNotifyType.warning);
    return;
  }
  const ar = (proxy.$refs.reqMainTableRef as any).getCurrentRecord();
  if (!ar || IsEmpty(ar) || IsEmpty(ar.reqTime)) {
    VxeMessage('请选中要删除的记录', VxeNotifyType.warning);
    return;
  }

  const type = await VXETable.modal.confirm('确定删除选中记录?'); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    const url = `/lab/reqMain/deleteReqMainById`;

    proxy.$http
      .post(url, ar)
      .then(async (res: any) => {
        //审核返回
        if (res && res.status && res.status.code && !IsEmpty(res.status.code) && res.status.code === 1) {
          findReqMainList(false);
        }
      })
      .catch((err: any) => {
        VxeMessage('取消检验失败', VxeNotifyType.error);
      });
  }
}

function reqMainRowClick({ row, isnotRefresh }: any) {
  if (IsEmpty(row)) {
    sltReqMain = {};
    clearReqMainForm();
    reqDetailList.length = 0;
    //feeItemList.length = 0;
    const $table = proxy.$refs.feeItemTableRef;
    if ($table) {
      $table.clearCheckboxRow();
    }
  } else {
    (proxy.$refs.reqMainTableRef as any).setCurrentRow(row);
    sltReqMain = row;
    setReqMainForm(row);

    if (!isnotRefresh) {
      findReqDetailList(false);
      //findFeeItemVsBarCodeList();
    }
  }
}
function setReqMainForm(row: any) {
  Object.assign(reqMainForm, row);
}
function clearReqMainForm() {
  for (const key in reqMainForm) {
    if (Object.prototype.hasOwnProperty.call(reqMainForm, key)) {
      if (key === 'labReqdetailList' || key === 'labMaininfoList') {
        reqMainForm[key] = [];
      } else {
        reqMainForm[key] = '';
      }
    }
  }
  reqMainForm.reqTime = searchForm.reqTime + ' 00:00:00';
}
function getBarCodeList() {
  barCodeList.length = 0;
  showLoading.value = true;
  const url = '/api/lab/labbarcodetype/findBarCodeTypeList';
  let obj = {
    keyWords: ''
  };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      barCodeList.push(...sortByField(res.data, 'barcodeNo', 'asc'));
      if (barCodeList.length > 0) {
        barCodeRowClick({ row: barCodeList[0] });
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showLoading.value = false;
    });
}

function barCodeRowClick({ row }: any) {
  (proxy.$refs.barCodeTypeTable as any).setCurrentRow(row);
  selevctBarCodeRow = row;

  findFeeItemVsBarCodeList();
  // getFeeItemList();
}

// 获取中间的项目信息
function findFeeItemVsBarCodeList() {
  feeItemList.length = 0;
  if (IsEmpty(sltInCompany.companyCode)) {
    return;
  }
  feeLoading.value = true;
  const url = '/lab/inspectCompFeeitem/findFeeitemListByBarCodeAndInspectCompany';
  proxy.$http
    .get(url, {
      params: {
        barcodeNo: selevctBarCodeRow.barcodeNo,
        companyCode: sltInCompany.companyCode
      }
    })
    .then((res: any) => {
      feeItemList.push(...res.data);

      proxy.$nextTick(() => {
        setFeeitemTableCheckBox();
      });
      feeLoading.value = false;
    })
    .catch((err: any) => {
      feeLoading.value = false;
    });
}

function findReqDetailList(isSaveReqMain: any) {
  reqDetailList.length = 0;
  dLoading.value = true;
  const url = '/api/reqdetail/getDetailByBarcode';
  proxy.$http
    .get(url, { params: { reqNo: sltReqMain.reqNo } })
    .then((res: any) => {
      reqDetailList.length = 0;
      reqDetailList.push(...res.data);
      //修改检验目的
      if (isSaveReqMain) {
        if (reqDetailList.length > 0) {
          reqMainForm.reqPurpose = reqDetailList.map((item: any) => item.feeName).join(',');
        } else {
          reqMainForm.reqPurpose = '';
        }
        saveReqMainForm();
      }
      proxy.$nextTick(() => {
        setFeeitemTableCheckBox();
      });
      dLoading.value = false;
    })
    .catch((err: any) => {
      dLoading.value = false;
      proxy.$alert(err, '提示');
    });
}

function deleteReqDetailList() {
  if (calcIsDisabled()) {
    VxeMessage('该数据已审核或上机，不能删除', VxeNotifyType.warning);
    return;
  }

  const selectRows = (proxy.$refs.reqDetailTableRef as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请选择需要删除的项目', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('确定删除数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const addDetailList = [];
        addDetailList.push(...selectRows);
        const data = { labReqdetailList: addDetailList };

        const url = '/api/reqdetail/batchDetelReqDetailList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            if (res.status.code != 1) {
              VxeMessage('删除失败', VxeNotifyType.error);
            } else {
              VxeMessage('删除成功', VxeNotifyType.success);
              findReqDetailList(true);
            }
          })
          .catch((err: any) => {
            proxy.$alert(err, '提示');
          });
      });
  }
}

function nextReqCode() {
  const a = autoIncrementNumber(reqMainForm.reqNo, '+');
  const rmObj = reqMainList.find((item: any) => item.reqNo == a);
  if (IsEmpty(rmObj)) {
    (proxy.$refs.reqMainTableRef as any).clearCurrentRow();
    clearReqMainForm();
    sltReqMain = {};
    reqDetailList.length = 0;
    //feeItemList.length = 0;
    const $table = proxy.$refs.feeItemTableRef;
    if ($table) {
      $table.clearCheckboxRow();
    }
    reqMainForm.reqNo = a;
    reqMainForm.reqTime = searchForm.reqTime + ' 00:00:00';
  } else {
    reqMainRowClick({ row: rmObj }); //默认选中第一条数据
  }
}

function prevReqCode() {
  const a = autoIncrementNumber(reqMainForm.reqNo, '-');
  const rmObj = reqMainList.find((item: any) => item.reqNo == a);
  if (IsEmpty(rmObj)) {
    (proxy.$refs.reqMainTableRef as any).clearCurrentRow();
    clearReqMainForm();
    sltReqMain = {};
    reqDetailList.length = 0;
    //feeItemList.length = 0;
    const $table = proxy.$refs.feeItemTableRef;
    if ($table) {
      $table.clearCheckboxRow();
    }
    reqMainForm.reqNo = a;
    reqMainForm.reqTime = searchForm.reqTime + ' 00:00:00';
  } else {
    reqMainRowClick({ row: rmObj }); //默认选中第一条数据
  }
}
function setFeeitemTableCheckBox() {
  const $table = proxy.$refs.feeItemTableRef;
  if ($table) {
    $table.clearCheckboxRow();
  }
  if (reqDetailList.length > 0) {
    const sltFeeItemList = [];
    for (const redo of reqDetailList) {
      const jj = feeItemList.find((item: any) => item.feeCode == redo.feeCode);
      if (!IsEmpty(jj)) {
        sltFeeItemList.push(jj);
      }
    }
    if ($table) {
      $table.setCheckboxRow(sltFeeItemList, true);
    }
  }
}

function feeItemChangeRow(checkedRows) {
  if (checkedRows.checked) {
    const addDetailList = [];
    const sltFeeItem = checkedRows.row;
    const sltReqDetail = reqDetailList.filter((p) => p.feeCode === sltFeeItem.feeCode);
    if (sltReqDetail.length > 0) {
      return;
    }
    const reqDetailObj = {
      reqNo: reqMainForm.reqNo,
      feeCode: sltFeeItem.feeCode,
      feeName: sltFeeItem.feeName,
      amount: 1,
      price: sltFeeItem.price,
      costs: sltFeeItem.price,
      isCharge: 1
    };
    addDetailList.push(reqDetailObj);
    const data = { labReqdetailList: addDetailList };
    const url = '/api/reqdetail/batchAddReqDetailList';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        findReqDetailList(true); // 获取检验仪器表格数据
        //VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  } else {
    const addDetailList = [];
    const sltFeeItem = checkedRows.row;
    const sltReqDetail = reqDetailList.filter((p) => p.feeCode === sltFeeItem.feeCode);
    addDetailList.push(...sltReqDetail);
    const data = { labReqdetailList: addDetailList };
    const url = '/api/reqdetail/batchDetelReqDetailList';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        findReqDetailList(true);
        //VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}

/**下拉选中行事件 */
function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    reqMainForm[r.aimKey] = e.row[r.rowKey];
  });
  // const strKey = JSON.stringify(e.aimKeys);
  // if (strKey.indexOf('inspectCompany') > -1) {
  //   findFeeItemVsBarCodeList();
  // }
  saveReqMainForm();
}

//#region  自定义指令
// 自定义指令
const enterNextInput: ObjectDirective<HTMLElement> = {
  mounted(el) {
    el.addEventListener('keypress', (e) => {
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      if (charcode == 13) {
        const doms: any = document.getElementsByClassName('enterNextInputFlag');
        let list = [];
        for (let i = 0; i < doms.length; i++) {
          let node = doms[i].childNodes;
          if (node.length > 0) {
            node.forEach((v) => {
              if ((v.nodeName == 'TEXTAREA' || v.nodeName == 'INPUT') && !v.disabled) {
                list.push(v);
              }
            });
          }
        }
        for (let j = 0; j <= list.length; j++) {
          if (list[j] == document.activeElement) {
            if (j == list.length - 1) {
              return;
            }
            list[j + 1].focus();
            return;
          }
        }
      }
    });
  }
};

// 使用自定义指令
proxy.$.directives = { enterNextInput: enterNextInput };
function calcIsDisabled() {
  if (IsEmpty(reqMainForm.state) || reqMainForm.state == '10') {
    return false;
  } else {
    return true;
  }
}

// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  return !calcIsDisabled();
}
</script>

<style lang="scss" scoped>
#checkregistDiv {
  height: 100%;

  .bodyContent {
    //height: calc(100% - 20px);
    height: 100%;

    .area {
      height: calc(100% - 20px);
      background-color: $base-white;

      .SplitpanesAll {
        .tableBox {
          height: calc(100% - 40px);
        }
        .tableMoSaBox {
          height: calc(100%);
        }
      }

      .lab-maininfo-right-tab {
        height: 100%;

        :deep(.el-tabs__nav-prev) {
          line-height: 28px !important;
        }

        :deep(.el-tabs__nav-next) {
          line-height: 28px !important;
        }

        :deep(.el-tabs__content) {
          height: 100%;
          padding: 2px;
        }

        :deep(.el-tab-pane) {
          height: 100%;
        }
      }
    }
  }
}

#checkregistDiv2 {
  :deep(.vxe-form) {
    padding-left: 1px;

    .vxe-input--inner,
    .vxe-textarea--inner,
    .vxe-button {
      background-color: transparent;
    }

    .vxe-input--inner[disabled] {
      color: #000;
    }

    // 遮罩层
    .vxe-loading {
      background: transparent;

      .vxe-loading--chunk {
        top: 35px;
      }
    }
  }
}
</style>